package by.alex.dzeshko.lastfmsimple.adapter;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import by.alex.dzeshko.lastfmsimple.R;
import by.alex.dzeshko.lastfmsimple.content.Contract;
import by.alex.dzeshko.lastfmsimple.images.ImageLoader;

public class ArtistsCursorAdapter extends CursorAdapter {

	public ArtistsCursorAdapter(Context context, Cursor c) {
		super(context, c, true);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (!mDataValid) {
			throw new IllegalStateException("this should only be called when the cursor is valid");
		}
		if (!mCursor.moveToPosition(position)) {
			throw new IllegalStateException("couldn't move cursor to position "	+ position);
		}
		View view;
		if (convertView == null) {
			view = newView(mContext, mCursor, parent);
			ViewHolder holder = new ViewHolder();
			holder.mArtistNameTextView = (TextView) view.findViewById(R.id.textview_adapter_artist_name);
			holder.mImageView = (ImageView) view.findViewById(R.id.imageview_adapter_artist);
			view.setTag(R.string.view_holder, holder);
		} else {
			view = convertView;
		}
		bindView(view, mContext, mCursor);
		return view;
	}

	@Override
	public void bindView(View view, final Context context, final Cursor cursor) {
		ViewHolder holder = (ViewHolder) view.getTag(R.string.view_holder);
		final String medium = cursor.getString(cursor.getColumnIndex(Contract.ArtistsColumns.IMAGE_MEDIUM));
		//final String original = cursor.getString(cursor.getColumnIndex(Contract.UpcomingColumns.POSTERS_ORIGINAL));
		if (!TextUtils.isEmpty(medium)) {
//			holder.mImageView.setOnClickListener(new OnClickListener() {
//				
//				@Override
//				public void onClick(View v) {
//					Intent intent = new Intent(context, FullScreenImageActivity.class);
//					intent.putExtra(POSTERS_PROFILE, poster);
//					intent.putExtra(POSTERS_ORIGINAL, original);
//					context.startActivity(intent);
//				}
//			});
			holder.mImageView.setImageBitmap(null);
			ImageLoader.getInstance().bind(this, holder.mImageView, medium);
		}
		holder.mArtistNameTextView.setText(cursor.getString(cursor.getColumnIndex(Contract.ArtistsColumns.NAME)));
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
		View view = View.inflate(context, R.layout.adapter_artist_list, null);
		return view;
	}

	// ViewHolder pattern implementation class
	static class ViewHolder {
		TextView mArtistNameTextView;

		ImageView mImageView;
	}

}
